#include <fcntl.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>


int main(int argc,char* argv[])
{
  int udp_fd = socket(AF_INET,SOCK_DGRAM,0);
  if(udp_fd < 0)
  {
    perror("socket fail");
    exit(-1);
  }
  
  struct sockaddr_in server_addr;
  server_addr.sin_port = htons(50000);
  server_addr.sin_family = AF_INET;
  inet_pton(AF_INET,"0.0.0.0",&server_addr.sin_addr);
  int ret = bind(udp_fd,(struct sockaddr*)&server_addr,sizeof(server_addr));
  

  struct sockaddr_in client;
  socklen_t len = sizeof(client);
  char buf[1024];
  recvfrom(udp_fd,buf,1024,0,(struct sockaddr*)&client,&len);
  printf("file name is %s\n",buf);
  char name[1024];
  snprintf(name,1024,"./aaa/%s",buf);
  printf("file name is %s\n",name);
  int file_fd = open(name,O_RDWR | O_CREAT,0644);
  if(file_fd < 0)
  {
    perror("open fail");
    return -1;
  }
  while(1)
  {
    memset(buf,0,1024);
    ret = recvfrom(udp_fd,buf,1024,0,(struct sockaddr*)&client,&len);
    if(ret < 1024)
    {
      write(file_fd,buf,ret);
      break;
    }else if(ret == 1024)
    {

      write(file_fd,buf,1024);
    }
  }

  close(udp_fd);
  close(file_fd);
  return 0;
}

